package sk.stuba.fiit.foo07.genex.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import sk.stuba.fiit.foo07.genex.beans.Answer;
import sk.stuba.fiit.foo07.genex.beans.Category;
import sk.stuba.fiit.foo07.genex.beans.Keyword;
import sk.stuba.fiit.foo07.genex.beans.Picture;
import sk.stuba.fiit.foo07.genex.beans.Question;
import sk.stuba.fiit.foo07.genex.beans.QuestionType;
import sk.stuba.fiit.foo07.genex.common.ResourceHelper;
import sk.stuba.fiit.foo07.genex.dao.CategoryDao;
import sk.stuba.fiit.foo07.genex.dao.CategoryDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.KeywordDao;
import sk.stuba.fiit.foo07.genex.dao.KeywordDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.PictureDao;
import sk.stuba.fiit.foo07.genex.dao.PictureDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionDao;
import sk.stuba.fiit.foo07.genex.dao.QuestionDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDao;
import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.UserDao;
import sk.stuba.fiit.foo07.genex.dao.UserDaoDerby;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */

public class NewQuestionDialog extends javax.swing.JDialog {
    /**
     * 
     */
    private static final long serialVersionUID = 1105455711110093349L;
    private ResourceHelper resHelp;
    private ImageIcon iconEdit;
    private ImageIcon iconAdd;
    private ImageIcon iconDelete;
    private CheckBoxTableModel model;
    private Question ret;
    private JButton jBtnExtend;
    private ArrayList<Category> actCategories;
    private QuestionDao qDao;
    private PictureDao pDao;
    private KeywordDao kDao;
    private QuestionTypeDao qtDao;
    private UserDao uDao;
    private ArrayList<QuestionType> questionTypes;
    private Connection connection;
    private DefaultListModel keywords;
    private DefaultListModel pictures;

    private JScrollPane jSclHint;
    private JList jLstKeywords;
    private JButton jBtnNewPicture;
    private JButton jBtnDeletePicture;
    private JButton jBtnDeleteKeyword;
    private JButton jBtnNewKeyword;
    private JLabel jLabel6;
    private JList jLstPictures;
    private JLabel jLabel5;
    private JScrollPane jScrollPane4;
    private JButton jBtnOK;
    private JLabel jLabel2;
    private JTable jTblAnswers;
    private JScrollPane jScrollPane2;
    private JComboBox jCbxDifficulty;
    private JScrollPane jScrollPane3;
    private ProgressCellRenderer jPbrDifficulty;
    private JLabel jLabel4;
    private JComboBox jCbxQuestionType;
    private JLabel jLabel3;
    private JButton jBtnDeleteAnswer;
    private JButton jBtnNewAnswer;
    private JButton jBtnEditAnswer;
    private JSeparator jSeparator2;
    private JSeparator jSeparator1;
    private JTextArea jTxtQuestionText;
    private JScrollPane jScrollPane1;
    private JLabel jLabel1;
    private JButton jBtnCancel;
    private JTextPane jTxtHint;

    public NewQuestionDialog(JFrame frame, ArrayList<Category> actual,
            Question question, Connection c) {
        super(frame);

        try {
            qDao = new QuestionDaoDerby(c);
            pDao = new PictureDaoDerby(c);
            qtDao = new QuestionTypeDaoDerby(c);
            kDao = new KeywordDaoDerby(c);
            uDao = new UserDaoDerby(c);
        } catch (SQLException e) {
            System.out
                    .println("SQLException: Can't create Dao instance. Connection=="
                            + c);
            e.printStackTrace();
        }

        resHelp = new ResourceHelper();
        connection = c;
        actCategories = actual;
        keywords = new DefaultListModel();
        pictures = new DefaultListModel();

        // inicializacia typov otazok
        //TODO
        //vynimkyyy
        try {
            questionTypes = qtDao.getAllQuestionTypes();
        } catch (Exception e) {
        }
        // model tabulky odpovedi
        model = new CheckBoxTableModel("Text", "Správna");

        initGUI(c);

        if (question != null) {
            setTitle("Upraviť otázku");
            ret = question;
            fillFields(ret);
            jBtnExtend.setEnabled(true);
        } else {
            setTitle("Nová otázka");
            ret = new Question();
            jBtnExtend.setEnabled(false);
        }
        CategoryDao cDao = new CategoryDaoDerby(c);
        try {
            if (question == null)
                throw new SQLException("OK");
            ArrayList<Integer> categoriesReal = cDao
                    .getCategoriesIDByQuestionID(question.getQuestionID());

            if (categoriesReal.size() > 1) {
                StringBuffer cats = new StringBuffer();

                for (Integer catID : categoriesReal) {
                    Category cat = cDao.getCategoryByID(catID);
                    if (catID != categoriesReal.get(0)) {
                        cats.append(", ");
                    }
                    cats.append(cat);
                }

                StringBuffer newCategories = new StringBuffer();
                for (Category cat : actCategories) {
                    if (cat != actCategories.get(0)) {
                        newCategories.append(", ");
                    }
                    newCategories.append(cat);
                }

                hint("Warning: Upravujete otázku ktorá sa nachádza v kategóriách: "
                        + cats
                        + "\nKategória/e pre novú otázku: "
                        + newCategories);
            } else
                hint("Info: Kliknutím na odpoveď sa v tomto poli zobrazí jej text.");

        } catch (SQLException ex) {
            hint("Info: Kliknutím na odpoveď sa v tomto poli zobrazí jej text.");
        }
    }

    private void initGUI(Connection connection) {
        try {
            iconEdit = new ImageIcon(resHelp
                    .getResourceBytes("/icons/edit.png"));
            iconAdd = new ImageIcon(resHelp.getResourceBytes("/icons/add.png"));
            iconDelete = new ImageIcon(resHelp
                    .getResourceBytes("/icons/remove.png"));

            // START >> this
            this.setTitle("Nová otázka");
            getContentPane().setLayout(null);
            this.setResizable(false);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            setLocationByPlatform(true);
            // START >> jSclHint
            jSclHint = new JScrollPane();
            getContentPane().add(jSclHint);
            jSclHint.setBounds(10, 11, 549, 64);
            // START >> jTxtHint
            jTxtHint = new JTextPane();
            jSclHint.setViewportView(jTxtHint);
            jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
            jTxtHint.setEditable(false);
            jTxtHint.setPreferredSize(new java.awt.Dimension(509, 40));
            // END << jTxtHint
            // END << jSclHint
            // START >> jBtnOK
            jBtnOK = new JButton();
            getContentPane().add(jBtnOK);
            jBtnOK.setText("OK");
            jBtnOK.setBounds(399, 488, 77, 23);
            jBtnOK.setMnemonic(java.awt.event.KeyEvent.VK_O);
            jBtnOK.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnOKActionPerformed(evt);
                }
            });
            // END << jBtnOK
            // START >> jBtnCancel
            jBtnCancel = new JButton();
            getContentPane().add(jBtnCancel);
            jBtnCancel.setText("Cancel");
            jBtnCancel.setBounds(482, 488, 77, 23);
            jBtnCancel.setMnemonic(java.awt.event.KeyEvent.VK_C);
            jBtnCancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnCancelActionPerformed(evt);
                }
            });
            // END << jBtnCancel
            // START >> jLabel1
            jLabel1 = new JLabel();
            getContentPane().add(jLabel1);
            jLabel1.setText("Text otázky:");
            jLabel1.setBounds(10, 89, 264, 14);
            jLabel1.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel1
            // START >> jScrollPane1
            jScrollPane1 = new JScrollPane();
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(10, 109, 264, 120);
            jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
            // START >> jTxtQuestionText
            jTxtQuestionText = new JTextArea();
            jScrollPane1.setViewportView(jTxtQuestionText);
            jTxtQuestionText.setBackground(new java.awt.Color(255, 255, 240));
            // END << jTxtQuestionText
            // END << jScrollPane1
            // START >> jSeparator1
            jSeparator1 = new JSeparator();
            getContentPane().add(jSeparator1);
            jSeparator1.setBounds(10, 477, 549, 11);
            // END << jSeparator1
            // START >> jSeparator2
            jSeparator2 = new JSeparator();
            getContentPane().add(jSeparator2);
            jSeparator2.setBounds(10, 80, 549, 9);
            // END << jSeparator2
            // START >> jLabel2
            jLabel2 = new JLabel();
            getContentPane().add(jLabel2);
            jLabel2.setText("Odpovede:");
            jLabel2.setBounds(10, 293, 264, 14);
            jLabel2.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel2
            // START >> jScrollPane2
            jScrollPane2 = new JScrollPane();
            getContentPane().add(jScrollPane2);
            jScrollPane2.setBounds(10, 313, 265, 122);
            // START >> jTblAnswers
            //jTblAnswers = new CheckBoxTable("Text", "Správna");
            jTblAnswers = new JTable(model);
            jTblAnswers.setBackground(new java.awt.Color(255, 255, 240));
            jTblAnswers.getColumnModel().getColumn(1).setMaxWidth(50);
            jTblAnswers.getColumnModel().getColumn(1).setResizable(false);
            jTblAnswers.getColumnModel().getColumn(0).setResizable(false);
            jTblAnswers.setShowGrid(false);
            jScrollPane2.setViewportView(jTblAnswers);
            jScrollPane2.getViewport().setBackground(
                    new java.awt.Color(255, 255, 240));
            jTblAnswers.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    int index = jTblAnswers.getSelectedRow();
                    if (index == -1)
                        return;
                    hint(model.getAnswer(index).toString());
                }
            });
            // END << jTblAnswers
            // END << jScrollPane2
            // START >> jBtnEditAnswer
            jBtnEditAnswer = new JButton();
            getContentPane().add(jBtnEditAnswer);
            jBtnEditAnswer.setBounds(229, 446, 21, 21);
            jBtnEditAnswer.setIcon(iconEdit);
            jBtnEditAnswer.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnEditAnswer.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnEditAnswer.setToolTipText("Upravi\u0165");
            jBtnEditAnswer.setActionCommand("Upravi\u0165");
            jBtnEditAnswer.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnEditAnswerActionPerformed(evt);
                }
            });
            // END << jBtnEditAnswer
            // START >> jBtnNewAnswer
            jBtnNewAnswer = new JButton();
            getContentPane().add(jBtnNewAnswer);
            jBtnNewAnswer.setBounds(203, 446, 21, 21);
            jBtnNewAnswer.setIcon(iconAdd);
            jBtnNewAnswer.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnNewAnswer.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnNewAnswer.setToolTipText("Nová");
            jBtnNewAnswer.setActionCommand("Nová");
            jBtnNewAnswer.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnNewAnswerActionPerformed(evt);
                }
            });
            // END << jBtnNewAnswer
            // START >> jBtnDeleteAnswer
            jBtnDeleteAnswer = new JButton();
            getContentPane().add(jBtnDeleteAnswer);
            jBtnDeleteAnswer.setBounds(255, 446, 21, 21);
            jBtnDeleteAnswer.setIcon(iconDelete);
            jBtnDeleteAnswer.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnDeleteAnswer.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnDeleteAnswer.setToolTipText("Odstráni\u0165");
            jBtnDeleteAnswer.setActionCommand("Odstráni\u0165");
            jBtnDeleteAnswer.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnDeleteAnswerActionPerformed(evt);
                }
            });
            // END << jBtnDeleteAnswer
            // START >> jLabel3
            jLabel3 = new JLabel();
            getContentPane().add(jLabel3);
            jLabel3.setText("Typ otázky:");
            jLabel3.setBounds(10, 240, 264, 14);
            jLabel3.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel3
            // START >> jCbxQuestionType
            ComboBoxModel jCbxQuestionTypeModel = new DefaultComboBoxModel(
                    questionTypes.toArray());
            jCbxQuestionType = new JComboBox();
            getContentPane().add(jCbxQuestionType);
            jCbxQuestionType.setModel(jCbxQuestionTypeModel);
            jCbxQuestionType.setBounds(10, 260, 264, 20);
            jCbxQuestionType.setBackground(new java.awt.Color(255, 255, 240));
            jCbxQuestionType.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent evt) {
                    jCbxQuestionTypeItemStateChanged(evt);
                }
            });
            // END << jCbxQuestionType
            // START >> jLabel4
            jLabel4 = new JLabel();
            getContentPane().add(jLabel4);
            jLabel4.setText("Zlo\u017eitos\u0165 otázky:");
            jLabel4.setBounds(294, 89, 175, 14);
            jLabel4.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel4
            // START >> jPbrDifficulty
            jPbrDifficulty = new ProgressCellRenderer();

            getContentPane().add(jPbrDifficulty);
            jPbrDifficulty.setBounds(294, 109, 207, 20);
            // END << jPbrDifficulty
            // START >> jScrollPane3
            jScrollPane3 = new JScrollPane();
            getContentPane().add(jScrollPane3);
            jScrollPane3.setBounds(294, 160, 265, 120);
            jScrollPane3.setBackground(new java.awt.Color(255, 255, 255));
            // START >> jLstKeywords
            jLstKeywords = new JList(keywords);
            jScrollPane3.setViewportView(jLstKeywords);
            jLstKeywords.setBackground(new java.awt.Color(255, 255, 240));
            jLstKeywords.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    if (evt.getClickCount() == 1)
                        hint("Info: Dvojklikom môžete vybrané kľúčové slovo vymazať.");
                    else
                        jBtnDeleteKeywordActionPerformed(new ActionEvent(
                                jLstKeywords, 0, null));
                }
            });
            // END << jLstKeywords
            // END << jScrollPane3
            // START >> jTfdDifficulty

            ComboBoxModel jTfdDifficultyModel = new DefaultComboBoxModel(
                    new String[] { "1", "2", "3", "4", "5" });
            jCbxDifficulty = new JComboBox();
            getContentPane().add(jCbxDifficulty);

            jCbxDifficulty.setModel(jTfdDifficultyModel);
            jCbxDifficulty.setBounds(511, 107, 48, 20);
            jCbxDifficulty.setBackground(new java.awt.Color(255, 255, 240));
            jCbxDifficulty.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jTfdDifficultyActionPerformed(evt);
                }
            });

            // END << jTfdDifficulty
            // START >> jScrollPane4
            jScrollPane4 = new JScrollPane();
            getContentPane().add(jScrollPane4);
            jScrollPane4.setBounds(294, 313, 265, 122);
            jScrollPane4.setBackground(new java.awt.Color(255, 255, 255));
            // START >> jLstPictures
            jLstPictures = new JList(pictures);
            jScrollPane4.setViewportView(jLstPictures);
            jLstPictures.setBackground(new java.awt.Color(255, 255, 240));
            jLstPictures.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent evt) {
                    if (jLstPictures.getSelectedIndex() != -1)
                        hint(((Picture) pictures.get(jLstPictures
                                .getSelectedIndex())).getDescription());
                }
            });
            jLstPictures.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    if (evt.getClickCount() == 1)
                        hint("Info: Dvojklikom môžete vybraný obrázok vymazať.");
                    else
                        jBtnDeletePictureActionPerformed(new ActionEvent(
                                jLstKeywords, 0, null));
                }
            });
            // END << jLstPictures
            // END << jScrollPane4
            // START >> jLabel5
            jLabel5 = new JLabel();
            getContentPane().add(jLabel5);
            jLabel5.setText("K\u013eú\u010dové slová:");
            jLabel5.setBounds(294, 138, 267, 14);
            jLabel5.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel5
            // START >> jLabel6
            jLabel6 = new JLabel();
            getContentPane().add(jLabel6);
            jLabel6.setText("Obrázky:");
            jLabel6.setBounds(294, 293, 183, 14);
            jLabel6.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel6
            // START >> jBtnNewKeyword
            jBtnNewKeyword = new JButton();
            getContentPane().add(jBtnNewKeyword);
            jBtnNewKeyword.setBounds(514, 284, 21, 21);
            jBtnNewKeyword.setIcon(iconAdd);
            jBtnNewKeyword.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnNewKeyword.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnNewKeyword.setToolTipText("Nové");
            jBtnNewKeyword.setActionCommand("ksNové");
            jBtnNewKeyword.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnNewKeywordActionPerformed(evt);
                }
            });

            // actiolistener na klikanie
            jPbrDifficulty.addMouseListener(new ProgressbarMouseHandler(
                    jPbrDifficulty, jCbxDifficulty));
            // koniec listenera

            // END << jBtnNewKeyword
            // START >> jBtnEditKeyword
            // END << jBtnEditKeyword
            // START >> jBtnDeleteKeyword
            jBtnDeleteKeyword = new JButton();
            getContentPane().add(jBtnDeleteKeyword);
            jBtnDeleteKeyword.setBounds(539, 284, 21, 21);
            jBtnDeleteKeyword.setIcon(iconDelete);
            jBtnDeleteKeyword.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnDeleteKeyword.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnDeleteKeyword.setToolTipText("Odstráni\u0165");
            jBtnDeleteKeyword.setActionCommand("ksOdstráni\u0165");
            jBtnDeleteKeyword.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnDeleteKeywordActionPerformed(evt);
                }
            });
            // END << jBtnDeleteKeyword
            // START >> jBtnNewPicture
            jBtnNewPicture = new JButton();
            getContentPane().add(jBtnNewPicture);
            jBtnNewPicture.setBounds(514, 446, 21, 21);
            jBtnNewPicture.setIcon(iconAdd);
            jBtnNewPicture.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnNewPicture.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnNewPicture.setToolTipText("Nový");
            jBtnNewPicture.setActionCommand("picNový");
            jBtnNewPicture.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnNewPictureActionPerformed(evt);
                }
            });
            // END << jBtnNewPicture
            // START >> jBtnDeletePicture
            jBtnDeletePicture = new JButton();
            getContentPane().add(jBtnDeletePicture);
            jBtnDeletePicture.setBounds(539, 446, 21, 21);
            jBtnDeletePicture.setIcon(iconDelete);
            jBtnDeletePicture.setVerticalTextPosition(SwingConstants.BOTTOM);
            jBtnDeletePicture.setHorizontalTextPosition(SwingConstants.CENTER);
            jBtnDeletePicture.setToolTipText("Odstráni\u0165");
            jBtnDeletePicture.setActionCommand("picOdstráni\u0165");
            {
                jBtnExtend = new JButton();
                getContentPane().add(jBtnExtend);
                jBtnExtend.setText("Ulo\u017ei\u0165 ako novú");
                jBtnExtend.setBounds(229, 488, 144, 23);
                jBtnExtend.setMnemonic(java.awt.event.KeyEvent.VK_U);
                jBtnExtend.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jBtnExtendActionPerformed(evt);
                    }
                });
            }
            jBtnDeletePicture.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnDeletePictureActionPerformed(evt);
                }
            });
            // END << jBtnDeletePicture
            // END << this
            this.setSize(577, 551);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jTfdDifficultyActionPerformed(ActionEvent evt) {
        jPbrDifficulty.setIntegerValue(jCbxDifficulty.getSelectedIndex() + 1);
    }

    private void jBtnNewAnswerActionPerformed(ActionEvent evt) {
        NewAnswerDialog nad = new NewAnswerDialog(this, null);
        nad.setLocationRelativeTo(null);
        Answer a = nad.showDialog();
        if (a == null)
            return;

        if (a.getText().length() == 0)
            hint("Warning: Musíte zadať text odpovede!");
        else
            model.addAnswer(a);
    }

    private void jBtnEditAnswerActionPerformed(ActionEvent evt) {
        // uprava odpovede
        int sel = jTblAnswers.getSelectedRow();

        if (sel == -1) {
            hint("Warning: Musíte vybrať odpoveď, ktorú chcete upraviť!");
            return;
        }

        NewAnswerDialog nad = new NewAnswerDialog(this, model.getAnswer(sel));
        nad.setLocationRelativeTo(null);
        Answer a = nad.showDialog();
        if (a == null)
            return;

        if (a.getText().length() == 0)
            hint("Warning: Musíte zadať text odpovede!");
        else
            model.setValueAt(a.getText(), sel, 0);
    }

    private void jBtnDeleteAnswerActionPerformed(ActionEvent evt) {
        // odobranie odpovede
        int sel = jTblAnswers.getSelectedRow();
        if (sel != -1)
            model.removeAnswer(sel);
        else
            hint("Warning: Musíte vybrať odpoveď, ktorú chcete odstrániť!");
    }

    private boolean hasKeyword(Keyword k) {
        for (int i = 0; i < keywords.size(); i++)
            if (k.getText().equals(((Keyword) (keywords.get(i))).getText()))
                return true;

        return false;
    }

    private boolean hasPicture(Picture p) {
        for (int i = 0; i < pictures.size(); i++)
            if (p.getPictureID() == ((Picture) pictures.get(i)).getPictureID())
                return true;

        return false;
    }

    private void jBtnNewKeywordActionPerformed(ActionEvent evt) {
        boolean hasDuplicity = false;
        NewKeywordDialog nkd = new NewKeywordDialog(this, connection);
        nkd.setLocationRelativeTo(null);
        Keyword[] k = nkd.showDialog();
        if (k != null) {
            for (int i = 0; i < k.length; i++)
                if (hasKeyword(k[i]) == false)
                    keywords.addElement(k[i]);
                else {
                    hasDuplicity = true;
                }
        }
        if (hasDuplicity)
            hint("Info: Niektoré kľúčové slová neboli pridané, lebo sa v zozname už nachádzajú.");
        else
            hint("Info: Všetky vybrané kľúčové slová boli úspešne pridané.");
    }

    private void jBtnDeleteKeywordActionPerformed(ActionEvent evt) {
        int sel = jLstKeywords.getSelectedIndex();

        if (sel == -1) {
            hint("Warning: Najprv musíte vybrať kľúčové slová, ktoré chcete odstrániť.");
            return;
        }

        while (sel != -1) {
            keywords.remove(sel);
            sel = jLstKeywords.getSelectedIndex();
        }
    }

    private void jBtnNewPictureActionPerformed(ActionEvent evt) {
        boolean hasDuplicity = false;
        NewPictureDialog npd = new NewPictureDialog(this, connection);
        npd.setLocationRelativeTo(null);
        Picture[] pixs = npd.showDialog();

        if (pixs == null)
            return;

        for (int i = 0; i < pixs.length; i++) {
            if (hasPicture(pixs[i]) == false)
                pictures.addElement(pixs[i]);
            else {
                hasDuplicity = true;
            }
        }

        if (hasDuplicity)
            hint("Info: Niektoré obrázky neboli pridané, lebo sa v zozname už nachádzajú.");
        else
            hint("Info: Všetky vybrané obrázky boli úspešne pridané.");
    }

    private void jBtnDeletePictureActionPerformed(ActionEvent evt) {
        int sel = jLstPictures.getSelectedIndex();

        if (sel == -1) {
            hint("Warning: Najprv musíte vybrať obrázky, ktoré chcete odstrániť.");
            return;
        }

        while (sel != -1) {
            pictures.remove(sel);
            sel = jLstPictures.getSelectedIndex();
        }
    }

    private void jBtnCancelActionPerformed(ActionEvent evt) {
        // ukoncenie formulara prikazom CANCEL
        ret = null;
        setVisible(false);
    }

    private void jBtnOKActionPerformed(ActionEvent evt) {
        // OK vsetko vyplnene , mozeme pridat otazku
        ret.setText(jTxtQuestionText.getText());
        ret.setQuestionTypeID(questionTypes.get(
                jCbxQuestionType.getSelectedIndex()).getQuestionTypeID());

        ret.setCreated(new Timestamp(0));
        ret.setLastUpdate(new Timestamp(0));
        //TODO
        //pridane odchytavanie vynimiek (palo)
        try {
            ret.setUserID(uDao.getDefaultTUser().getUserID());
        } catch (Exception e) {
        }
        ret.setDifficulty(jCbxDifficulty.getSelectedIndex() + 1);
        //TODO 
        //pridane odchytavanie vynimky (palo)
        try {
            if (evt == null) {
                // ked sme tu znamena ze toto robime odvodenu otazku
                if (actCategories.size() != 0) {
                    for (Category c : actCategories) {
                        qDao.addQuestion(c.getCategoryID(), ret);
                    }
                } else {
                    qDao.createQuestion(ret); //vytvorenie novej bez kategorie
                }
            } else {
                if (ret.getQuestionID() != null) {
                    qDao.updateQuestion(ret.getQuestionID(), ret); //uprava existujucej
                } else {
                    qDao.addQuestion(actCategories.get(0).getCategoryID(), ret); // vytvarame novu
                }
            }
        } catch (Exception e) {
            hint("Error: " + e.getLocalizedMessage());
            return;
        }
        // ulozenie odpovedi
        model.saveAnswers(ret, connection);

        // ulozenie klucovych slov
        int i, size = keywords.size();
        //TODO
        //pozret
        try {
            kDao.deleteAllKeywordsFromQuestion(ret.getQuestionID());
            for (i = 0; i < size; i++)
                kDao.addKeyword(ret.getQuestionID(), (Keyword) keywords.get(i));
        } catch (Exception e) {
            hint("Error: " + e.getLocalizedMessage());
            return;
        }
        // a nakoniec obrazky
        ArrayList<Picture> pixs = null;
        //TODO 
        //pridane odchytavanie vynimky (palo)
        try {
            pixs = pDao.getPicturesByQuestionID(ret.getQuestionID());

            for (Picture p : pixs)
                pDao.deletePictureFromQuestion(p.getPictureID(), ret
                        .getQuestionID());
            for (i = 0; i < pictures.size(); i++)
                pDao.addPictureToQuestion(((Picture) pictures.get(i))
                        .getPictureID(), ret.getQuestionID());
        } catch (Exception e) {
            hint("Error: " + e.getLocalizedMessage());
            return;
        }
        setVisible(false);
    }

    private void hint(String text) {
        if (jTxtHint.getBackground() == GenexGUI.COMB1_BACKGROUND_COLOR) {
            jTxtHint.setBackground(GenexGUI.COMB2_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB2_FOREGROUND_COLOR);
        } else {
            jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
        }
        if (text.startsWith("Error:")) {
            jTxtHint.setText(text.substring(6));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/error.png")));
        } else if (text.startsWith("Warning:")) {
            jTxtHint.setText(text.substring(8));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/warning.png")));
        } else if (text.startsWith("Info:")) {
            jTxtHint.setText(text.substring(5));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/info.png")));
        } else {
            jTxtHint.setText(text);
        }
    }

    public Question showDialog() {
        this.setModalityType(ModalityType.DOCUMENT_MODAL);

        setVisible(true);
        return ret;
    }

    public void fillFields(Question q) {
        jTxtQuestionText.setText(q.getText());

        for (int i = 0; i < questionTypes.size(); i++)
            if (questionTypes.get(i).getQuestionTypeID() == q
                    .getQuestionTypeID())
                jCbxQuestionType.setSelectedIndex(i);

        model.setAnswers(q, connection);

        jCbxDifficulty.setSelectedIndex(q.getDifficulty() - 1);
        jPbrDifficulty.setIntegerValue(q.getDifficulty());

        keywords.clear();
        //TODO
        //pozret
        try {
            ArrayList<Keyword> keys = kDao.getKeywordsByQuestionID(q
                    .getQuestionID());
            for (Keyword key : keys)
                keywords.addElement(key);
        } catch (Exception e) {
        }
        ArrayList<Picture> pixs = null;
        //TODO
        //vynimky
        try {
            pixs = pDao.getPicturesByQuestionID(q.getQuestionID());
            for (Picture pic : pixs)
                pictures.addElement(pic);
        } catch (Exception e) {
        }
        jLstKeywords.updateUI();
        jLstPictures.updateUI();
        jTxtQuestionText.setCaretPosition(0);
    }

    private void jCbxQuestionTypeItemStateChanged(ItemEvent evt) {
        QuestionType qType = (QuestionType) jCbxQuestionType.getSelectedItem();
        hint(qType.getDescription());
        String qt = qType.getName();

        if ("Single choice".equals(qt)) {
            jTblAnswers.setEnabled(true);
            model.setSingleSelect(true);
            jBtnNewAnswer.setEnabled(true);
            jBtnEditAnswer.setEnabled(true);
            jBtnDeleteAnswer.setEnabled(true);
        } else if ("Multi choice".equals(qt)) {
            jTblAnswers.setEnabled(true);
            model.setSingleSelect(false);
            jBtnNewAnswer.setEnabled(true);
            jBtnEditAnswer.setEnabled(true);
            jBtnDeleteAnswer.setEnabled(true);
        } else if ("True/False".equals(qt)) {
            jTblAnswers.setEnabled(true);
            model.setSingleSelect(true);
            model.setAnswers(null);
            model.addAnswer(new Answer("Ano", true, 0, null));
            model.addAnswer(new Answer("Nie", false, 0, null));
            jBtnNewAnswer.setEnabled(false);
            jBtnEditAnswer.setEnabled(true);
            jBtnDeleteAnswer.setEnabled(false);
        } else if ("Fill in".equals(qt)) {
            jTblAnswers.setEnabled(false);
            model.setSingleSelect(false);
            model.setAnswers(null);
            jBtnNewAnswer.setEnabled(false);
            jBtnEditAnswer.setEnabled(false);
            jBtnDeleteAnswer.setEnabled(false);
        } else if ("Essay".equals(qt)) {
            model.setAnswers(null);
            jTblAnswers.setEnabled(false);
            jBtnNewAnswer.setEnabled(false);
            jBtnEditAnswer.setEnabled(false);
            jBtnDeleteAnswer.setEnabled(false);
        }

        model.fireTableDataChanged();
    }

    private void jBtnExtendActionPerformed(ActionEvent evt) {

        // we set derivedFrom to "root" derived question (always the first original question)
        if (ret.getDerivedFromID() == null) {
            ret.setDerivedFromID(ret.getQuestionID());
        }

        jBtnOKActionPerformed(null);
    }
}
